from django.shortcuts import render, redirect, HttpResponse
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.urls import reverse
from web.forms.wiki import WikiModelForm
from utils.safe.encrypt import uid
from utils.tencent.cos import upload_file
from web import models

def wiki(request, project_id):
    """ wiki首页 """
    wiki_id = request.GET.get("wiki_id")
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, "web/wiki.html")
    if wiki_id:
        wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, "web/wiki.html", {'wiki_object': wiki_object})

def wiki_add(request, project_id):
    """ 添加wiki """
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'web/wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.saas.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    return render(request, 'web/wiki_form.html', {'form': form})

def wiki_catalog(request, project_id):
    """ 获取wiki目录 """

    # 获取当前项目所有的目录
    # QuerySet类型，其中每个元素都是一个元组，如果想要序列化，需要将其转换成列表类型
    # data = models.Wiki.objects.filter(project=request.saas.project).values_list('id', 'title', 'parent_id')
    # 返回的是QuerySet类型，其中每个元素是一个字典
    data = models.Wiki.objects.filter(project=request.saas.project).values('id', 'title', 'parent_id').order_by('depth', 'id')

    return JsonResponse({'status': True, 'data': list(data)})

def wiki_delete(request, project_id, wiki_id):
    """ 删除Wiki """
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)

def wiki_edit(request, project_id, wiki_id):
    """ 编辑文章 """
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'web/wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = "{}?wiki_id={}".format(url, wiki_id)
        return redirect(preview_url)

    return render(request, 'web/wiki_form.html', {'form': form})

@csrf_exempt
@xframe_options_sameorigin
def wiki_upload(request, project_id):
    """ markdown插件上传图片 """

    # markdown编辑器规定的返回格式
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    image_object = request.FILES.get("editormd-image-file")
    # print(image_object, image_object.name)
    if not image_object:
        result['message'] = "文件不存在"
        return JsonResponse(result)

    # 将文件对象上传到当前项目的桶中
    bucket = request.saas.project.bucket
    ext = image_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.saas.user.mobile_phone), ext)
    img_url = upload_file(
        bucket,
        request.saas.project.region,
        image_object,
        key
    )
    result['success'] = 1
    result['url'] = img_url

    # print(result)
    return JsonResponse(result)

